package com.project.yunshitong;

import static android.content.ContentValues.TAG;
import static com.project.yunshitong.Utils.getToast;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.project.yunshitong.adapter.InventoryAdapter;
import com.project.yunshitong.bean.DepartmentBean;
import com.project.yunshitong.bean.GoodsInfo;
import com.project.yunshitong.utils.ACache;
import com.project.yunshitong.utils.MySQLiteOpenHelper;
import com.project.yunshitong.utils.SoundTool;
import com.project.yunshitong.utils.ThreadPoolManager;
import com.seuic.scankey.IKeyEventCallback;
import com.seuic.scankey.ScanKeyService;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;
import com.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;

import java.util.ArrayList;
import java.util.List;

public class InventoryActivity extends AppCompatActivity implements View.OnClickListener, DecodeInfoCallBack {

    private ListView lvInventory;
    private Context context;
    private InventoryAdapter adapter;
    private ImageView ivBack;
    private TextView tvDischarged;
    private View viewDischarged;
    private RelativeLayout rlDischarged;
    private TextView tvUnpacked;
    private View viewUnpacked;
    private RelativeLayout rlUnpacked;
    private int state = 1;//0未盘 1已盘 2没有当前条码的盘盈 3待确认 4不属于当前部门的盘盈

    private List<DepartmentBean> departmentBeanList = new ArrayList<>();//部门数组
    private List<String> departmentList = new ArrayList<>();//部门名称数组
    private List<String> statusList = new ArrayList<>();//状态筛选数组
    private int departmentIndex = 0;


    private List<GoodsInfo> list = new ArrayList<>();//资产数组
    private List<GoodsInfo> isConfirmList = new ArrayList<>();//待确定数组
    private MySQLiteOpenHelper dbHelper1;
    private SQLiteDatabase sqliteDatabase1;
    private SQLiteDatabase sqliteDatabase4;
    private EditText etSearch;
    private TextView tvSearch;

    private Intent intent;

//    private LoadingDialog loadingDialog;

    private ArrayList<String> epcStringList = new ArrayList<>();

    /**
     * 扫描
     */
    private UHFService UTouchUHF;
    private boolean init;
    public static boolean mInventoryStart = false;
    private ScanKeyService mScanKeyService;
    private IKeyEventCallback mCallback;
    int Num = 0;
    private ImageView ivWifi;
    private TextView tvWifi;
    private Spinner spinnerInventory;
    private RadioButton rbOnly;
    private RadioButton rbNotOnly;
    private TextView tvProfit;
    private View viewProfit;
    private RelativeLayout rlProfit;
    private LinearLayout llNoProfit;

    private Scanner scanner;
    private ImageView ivSetting;
    private LinearLayout llClear;
    private TextView tvConfirmed;
    private View viewConfirmed;
    private RelativeLayout rlConfirmed;
    private TextView tvOperation;

    private ACache aCache;
    private LinearLayout llInventory;
    private TextView tvGoodNo;


    private int sortFlag = 0;//0默认状态 1升序  2降序
    private int sortType = 0;//0默认状态 1资产编号  2资产名称 3
    private TextView tvGoodName;
    private CheckBox cbChange;
    private TextView tvGoodStatus;
    private Spinner spinnerStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);
        dbHelper1 = new MySQLiteOpenHelper(this, "goods_info");
        sqliteDatabase4 = dbHelper1.getReadableDatabase();
        sqliteDatabase1 = dbHelper1.getWritableDatabase();
        context = this;
        aCache = ACache.get(context);
//        loadingDialog = new LoadingDialog(context, "数据加载中", 1);
        InitRfid();
        initView();
        changeView(1);
//        Toast.makeText(context, 1, Toast.LENGTH_SHORT).show();
    }

    private void initView() {
        lvInventory = findViewById(R.id.lvInventory);
//        setAdapter();
        ivBack = findViewById(R.id.ivBack);
        tvDischarged = findViewById(R.id.tvDischarged);
        viewDischarged = findViewById(R.id.viewDischarged);
        rlDischarged = findViewById(R.id.rlDischarged);
        tvUnpacked = findViewById(R.id.tvUnpacked);
        viewUnpacked = findViewById(R.id.viewUnpacked);
        rlUnpacked = findViewById(R.id.rlUnpacked);
        ivBack.setOnClickListener(this);
        rlDischarged.setOnClickListener(this);
        rlUnpacked.setOnClickListener(this);
        etSearch = findViewById(R.id.etSearch);
        tvSearch = findViewById(R.id.tvSearch);
        tvSearch.setOnClickListener(this);
        ivWifi = findViewById(R.id.ivWifi);
        tvWifi = findViewById(R.id.tvWifi);
        spinnerInventory = findViewById(R.id.spinnerInventory);
        rbOnly = findViewById(R.id.rbOnly);
        rbNotOnly = findViewById(R.id.rbNotOnly);
        tvProfit = findViewById(R.id.tvProfit);
        viewProfit = findViewById(R.id.viewProfit);
        rlProfit = findViewById(R.id.rlProfit);
        rlProfit.setOnClickListener(this);
        llNoProfit = findViewById(R.id.llNoProfit);
        ivSetting = findViewById(R.id.ivSetting);
        ivSetting.setOnClickListener(this);
        llClear = findViewById(R.id.llClear);
        llClear.setOnClickListener(this);
        tvConfirmed = findViewById(R.id.tvConfirmed);
        viewConfirmed = findViewById(R.id.viewConfirmed);
        rlConfirmed = findViewById(R.id.rlConfirmed);
        rlConfirmed.setOnClickListener(this);
        tvOperation = findViewById(R.id.tvOperation);
        cbChange = findViewById(R.id.cbChange);
        if ("1".equals(aCache.getAsString("checkStatus"))) {//只扫IT开头
            rbOnly.setChecked(true);
            rbNotOnly.setChecked(false);
        } else {
            rbOnly.setChecked(false);
            rbNotOnly.setChecked(true);
        }
        llInventory = findViewById(R.id.llInventory);
        llInventory.setOnClickListener(this);
        tvGoodNo = findViewById(R.id.tvGoodNo);
        tvGoodNo.setOnClickListener(this);
        tvGoodName = findViewById(R.id.tvGoodName);
        tvGoodName.setOnClickListener(this);
        tvGoodStatus = findViewById(R.id.tvGoodStatus);
        spinnerStatus = findViewById(R.id.spinnerStatus);
        cbChange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    aCache.put("change", "1");
                } else {
                    aCache.put("change", "0");
                }
            }
        });
        if (aCache.getAsString("change") == null) {
            cbChange.setChecked(true);
        } else {
            if ("0".equals(aCache.getAsString("change"))) {
                cbChange.setChecked(false);
            } else {
                cbChange.setChecked(true);
            }
        }
        initData();
    }

    private void initData() {
        Cursor cursor;
        cursor = sqliteDatabase4.query("department", null, null, null,
                null, null, null);
        list.clear();
        DepartmentBean bean = new DepartmentBean("999999", "999999", "请选择");
        departmentList.add("请选择");
        departmentBeanList.add(bean);
        while (cursor.moveToNext()) {
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String superior = cursor.getString(cursor.getColumnIndex("superior"));
            @SuppressLint("Range") String departId = cursor.getString(cursor.getColumnIndex("departId"));
            DepartmentBean departmentBean = new DepartmentBean(departId, superior, name);
//            Log.e(TAG, "initData: 获取的数据=====" + departmentBean);
            departmentList.add(name);
            departmentBeanList.add(departmentBean);
        }
        statusList.add("状态");
        statusList.add("盘存");
        statusList.add("盘盈");

        initSpinner();
        initStatusSpinner();
    }

    private void initSpinner() {
        ArrayAdapter siteAdapter = new ArrayAdapter(this, R.layout.item_select, departmentList);
        spinnerInventory.setAdapter(siteAdapter);
        spinnerInventory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e(TAG, "onItemSelected: departmentBeanList.get()=======" + departmentBeanList.get(i));
                if (i != departmentIndex) {
                    epcStringList.clear();
                    isConfirmList.clear();
                }
//                if (i != departmentIndex && departmentIndex != 0) {
//                    AlertDialog alertDialog = new AlertDialog.Builder(context)
//                            .setTitle("重置盘点部门")
//                            .setMessage("确定重置盘点部门吗？" +
//                                    "重置之后清空当前盘点状态，重新盘点")
//                            .setPositiveButton("确定", (dialog, which) -> {
//                                departmentIndex = i;
////                                sqliteDatabase4.beginTransaction();
////                                Cursor cursor = sqliteDatabase4.query("goods", null, "state!=?",
////                                        new String[]{"0"}, null, null, null);
////                                while (cursor.moveToNext()) {
////                                    @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
////                                    GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
////                                    if (goodsInfo.getStatus().equals("2")) {//盘盈的数据全部删除
////                                        sqliteDatabase1.delete("goods", "fixedNumber=?", new String[]{goodsInfo.getFixedNumber()});
////                                    } else {
////                                        goodsInfo.setStatus("0");
////                                        ContentValues contentValues = new ContentValues();
////                                        contentValues.put("name", goodsInfo.getName());
////                                        contentValues.put("number", goodsInfo.getCode());
////                                        contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
////                                        contentValues.put("state", "0");
////                                        contentValues.put("deptid", goodsInfo.getDeptid());
////                                        contentValues.put("department", goodsInfo.getDepartment());
////                                        contentValues.put("json", new Gson().toJson(goodsInfo));
////                                        int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
////                                                new String[]{goodsInfo.getFixedNumber()});
////                                    }
////                                }
////                                sqliteDatabase4.setTransactionSuccessful();
////                                sqliteDatabase4.endTransaction();
//                                changeView(state);
//                            })
//                            .setNegativeButton("取消", (dialogInterface, i1) -> {
//                                spinnerInventory.setSelection(departmentIndex);
//                            }).create();
//                    alertDialog.show();
//                    return;
//                }
                departmentIndex = i;
                changeView(state);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initStatusSpinner() {
        ArrayAdapter siteAdapter = new ArrayAdapter(this, R.layout.item_select, statusList);
        spinnerStatus.setAdapter(siteAdapter);
        spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                int Status = i;//0;所有  1；盘存 2；盘盈
                sqliteDatabase4.beginTransaction();
                Cursor cursor;
                String orderBy = "";
                String sortF = "";
                if (sortFlag == 1) {
                    sortF = "asc";
                } else {
                    sortF = "desc";
                }
                switch (sortType) {
                    case 1:
                        orderBy = "number ";
                        break;
                    case 2:
                        orderBy = "name ";
                        break;
                    default:
                        orderBy = "time ";
                        break;
                }
                orderBy = orderBy + sortF;
                //部门的盘存和盘盈
                switch (Status) {
                    case 0:
                        if (departmentIndex == 0) {
                            cursor = sqliteDatabase4.query("goods", null, "state=? or state=?",
                                    new String[]{"1", "3"},
                                    null, null, orderBy);
                        } else {
                            cursor = sqliteDatabase4.query("goods", null, "(state=? or state=?) and deptid=?",
                                    new String[]{"1", "3", departmentBeanList.get(departmentIndex).getDepartId()},
                                    null, null, orderBy);
                        }
                        break;
                    case 1:
                        if (departmentIndex == 0) {
                            cursor = sqliteDatabase4.query("goods", null, "state=?",
                                    new String[]{"1"},
                                    null, null, orderBy);
                        } else {
                            cursor = sqliteDatabase4.query("goods", null, "state=?  and deptid=?",
                                    new String[]{"1", departmentBeanList.get(departmentIndex).getDepartId()},
                                    null, null, orderBy);
                        }
                        break;
                    case 2:
                        if (departmentIndex == 0) {
                            cursor = sqliteDatabase4.query("goods", null, "state=?",
                                    new String[]{"3"},
                                    null, null, orderBy);
                        } else {
                            cursor = sqliteDatabase4.query("goods", null, "state=?  and deptid=?",
                                    new String[]{"3", departmentBeanList.get(departmentIndex).getDepartId()},
                                    null, null, orderBy);
                        }
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + Status);
                }
                list.clear();
                while (cursor.moveToNext()) {
                    @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
                    GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
//            Log.e(TAG, "changeView: 获取的数据=========" + goodsInfo.toString());
                    list.add(goodsInfo);
                }
                sqliteDatabase4.setTransactionSuccessful();
                sqliteDatabase4.endTransaction();
                switch (state) {
                    case 0:
                        tvUnpacked.setText("未盘（" + list.size() + "）");
                        tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                        tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                        tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                        break;
                    case 1:
                        tvDischarged.setText("已盘（" + list.size() + "）");
                        tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                        tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                        tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                        break;
                    case 2:
                        tvProfit.setText("盘盈（" + list.size() + "）");
                        tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                        tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                        tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                        break;
                    case 3:
                        list.addAll(isConfirmList);
                        tvConfirmed.setText("待确认（" + list.size() + "）");
                        tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                        tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                        tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                        break;
                }
                setAdapter();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void setAdapter() {
        adapter = new InventoryAdapter(context, list);
        lvInventory.setAdapter(adapter);
        adapter.setClick(new InventoryAdapter.Callback() {
            @Override
            public void cancel(int index) {
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setTitle("取消待确认")
                        .setMessage("确定将该资产取消待确认吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            GoodsInfo goodsInfo = list.get(index);
                            isConfirmList.remove(goodsInfo);
                            /*goodsInfo.setStatus("3");
                            goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                            goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                            ContentValues contentValues = new ContentValues();
                            contentValues.put("name", goodsInfo.getName());
                            contentValues.put("number", goodsInfo.getCode());
                            contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                            contentValues.put("state", "3");
                            contentValues.put("deptid", goodsInfo.getDeptid());
                            contentValues.put("department", goodsInfo.getDepartment());
                            contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                            contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                            contentValues.put("time", System.currentTimeMillis());
                            contentValues.put("json", new Gson().toJson(goodsInfo));
                            int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                                    new String[]{goodsInfo.getFixedNumber()});
                            Log.e(TAG, "ReadRFIDOne2: status=====" + status);*/
                            changeView(state);
                        })
                        .setNegativeButton("取消", (dialogInterface, i1) -> {

                        }).create();
                alertDialog.show();
            }

            @Override
            public void click(int index) {
                if (departmentIndex == 0) {
                    getToast(context, "请先选择部门！");
                    return;
                }
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setTitle("修改部门")
                        .setMessage("确定将该资产部门修改成当前部门吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            GoodsInfo goodsInfo = list.get(index);
                            isConfirmList.remove(goodsInfo);
                            goodsInfo.setStatus("3");
                            goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                            goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                            ContentValues contentValues = new ContentValues();
                            contentValues.put("name", goodsInfo.getName());
                            contentValues.put("number", goodsInfo.getCode());
                            contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                            contentValues.put("state", "3");
                            contentValues.put("deptid", goodsInfo.getDeptid());
                            contentValues.put("department", goodsInfo.getDepartment());
                            contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                            contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                            contentValues.put("time", System.currentTimeMillis());
                            contentValues.put("json", new Gson().toJson(goodsInfo));
                            int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                                    new String[]{goodsInfo.getFixedNumber()});
                            Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                            changeView(state);
                        })
                        .setNegativeButton("取消", (dialogInterface, i1) -> {

                        }).create();
                alertDialog.show();
            }

            @Override
            public void changeState(int index, String status) {
                if (departmentIndex == 0) {
                    getToast(context, "请先选择部门！");
                    return;
                }
                String message = "";
                if ("0".equals(status)) {
                    message = "盘存吗？";
                } else {
                    message = "未盘点吗？";
                }
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setTitle("修改盘点状态")
                        .setMessage("确定将该资产盘点状态修改成" + message)
                        .setPositiveButton("确定", (dialog, which) -> {
                            GoodsInfo goodsInfo = list.get(index);
                            if ("0".equals(status)) {
                                goodsInfo.setStatus("1");
                            } else {
                                goodsInfo.setDeptid(goodsInfo.getOldDeptid());
                                goodsInfo.setDepartment(goodsInfo.getOldDepartment());
                                goodsInfo.setStatus("0");
                            }
                            ContentValues contentValues = new ContentValues();
                            contentValues.put("name", goodsInfo.getName());
                            contentValues.put("number", goodsInfo.getCode());
                            contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                            if ("0".equals(status)) {
                                contentValues.put("state", "1");
                            } else {
                                contentValues.put("state", "0");
                            }
                            contentValues.put("deptid", goodsInfo.getDeptid());
                            contentValues.put("department", goodsInfo.getDepartment());
                            contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                            contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                            contentValues.put("time", System.currentTimeMillis());
                            contentValues.put("json", new Gson().toJson(goodsInfo));
                            int status1 = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                                    new String[]{goodsInfo.getFixedNumber()});
                            Log.e(TAG, "ReadRFIDOne2: status=====" + status1);
                            getToast(context, "修改成功！");
                            changeView(state);
                        })
                        .setNegativeButton("取消", (dialogInterface, i1) -> {

                        }).create();
                alertDialog.show();
            }

            @Override
            public void change(int index) {
                final String[] items = departmentList.toArray(new String[0]);
                selectedItemPosition = -1;
                // 创建并显示对话框
                new AlertDialog.Builder(context)
                        .setTitle("请选择一个选项")
                        .setSingleChoiceItems(items, -1, (dialog, which) -> {
                            Log.e(TAG, "change: ====" + which);
                            String selectedOption = departmentList.get(which);
                            Log.e(TAG, "change: selectedOption====" + selectedOption);
                            selectedItemPosition = which;
                            // 处理选择项
                            // 可以在这里处理选择后的逻辑
                        })
                        .setPositiveButton("确定", (dialog, which) -> {
                            if (selectedItemPosition == 0 || selectedItemPosition == -1) {
                                Toast.makeText(context, "请选择更换的部门！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Log.e(TAG, "change: 确定====" + selectedItemPosition);
                            // 确定按钮点击事件
                            // 可以在这里处理最终的选择结果
                            String selectedOption = departmentList.get(selectedItemPosition);
                            Log.e(TAG, "change: selectedOption====" + selectedOption);
                            GoodsInfo goodsInfo = list.get(index);
//                            goodsInfo.setStatus("3");
                            goodsInfo.setDeptid(departmentBeanList.get(selectedItemPosition).getDepartId());
                            goodsInfo.setDepartment(departmentBeanList.get(selectedItemPosition).getDepartName());
                            ContentValues contentValues = new ContentValues();
                            contentValues.put("name", goodsInfo.getName());
                            contentValues.put("number", goodsInfo.getCode());
                            contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                            contentValues.put("state", "3");
                            contentValues.put("deptid", goodsInfo.getDeptid());
                            contentValues.put("department", goodsInfo.getDepartment());
                            contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                            contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                            contentValues.put("time", System.currentTimeMillis());
                            contentValues.put("json", new Gson().toJson(goodsInfo));
                            int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                                    new String[]{goodsInfo.getFixedNumber()});
                            Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                            changeView(state);
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 取消按钮点击事件
                            dialog.dismiss();
                        })
                        .show();
            }
        });
        adapter.notifyDataSetChanged();
    }

    int selectedItemPosition;//更改部门需要的下标

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.rlDischarged:
                changeView(1);
                break;
            case R.id.rlUnpacked:
                changeView(0);
                break;
            case R.id.tvSearch:
                if (etSearch.getText().toString().isEmpty()) {
                    getToast(context, "请输入要搜索的内容");
                    return;
                }
                Cursor cursor;
                if (state == 1) {
                    cursor = sqliteDatabase4.query("goods", null, "(state=? or state=?) and deptid=? and (number LIKE?  or name LIKE?)",
                            new String[]{String.valueOf(state), "3", departmentBeanList.get(departmentIndex).getDepartId(), "%" + etSearch.getText().toString().trim() + "%", "%" + etSearch.getText().toString().trim() + "%"},
                            null, null, null);
                } else {
                    cursor = sqliteDatabase4.query("goods", null, "state=? and deptid=?  and (number LIKE?  or name LIKE?)",
                            new String[]{String.valueOf(state), departmentBeanList.get(departmentIndex).getDepartId(), "%" + etSearch.getText().toString().trim() + "%", "%" + etSearch.getText().toString().trim() + "%"},
                            null, null, null);
                }
                list.clear();
                while (cursor.moveToNext()) {
                    @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
                    GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
                    Log.e(TAG, "onClick: 搜索的数据======" + goodsInfo);
                    list.add(goodsInfo);
                }
                setAdapter();
                break;
            case R.id.rlProfit:
                changeView(2);
                break;
            case R.id.ivSetting:
                intent = new Intent(context, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.llClear:
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setTitle("清空数据")
                        .setMessage("确定要清空所有数据吗？\n" +
                                "清空之后需要重新盘点")
                        .setPositiveButton("确定", (dialog, which) -> {
                            epcStringList.clear();
                            sqliteDatabase4.beginTransaction();
                            Cursor cursor1 = sqliteDatabase4.query("goods", null, "state!=?",
                                    new String[]{"0"}, null, null, null);
                            while (cursor1.moveToNext()) {
                                @SuppressLint("Range") String json = cursor1.getString(cursor1.getColumnIndex("json"));
                                GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
                                if (goodsInfo.getStatus().equals("2")) {//盘盈的数据全部删除
                                    sqliteDatabase1.delete("goods", "fixedNumber=? and deptid=?",
                                            new String[]{goodsInfo.getFixedNumber(), departmentBeanList.get(departmentIndex).getDepartId()});
                                } else {
                                    goodsInfo.setStatus("0");
                                    goodsInfo.setDepartment(goodsInfo.getOldDepartment());
                                    goodsInfo.setDeptid(goodsInfo.getOldDeptid());
                                    ContentValues contentValues = new ContentValues();
                                    contentValues.put("name", goodsInfo.getName());
                                    contentValues.put("number", goodsInfo.getCode());
                                    contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                                    contentValues.put("state", "0");
                                    contentValues.put("deptid", goodsInfo.getOldDeptid());
                                    contentValues.put("department", goodsInfo.getOldDepartment());
                                    contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                                    contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                                    contentValues.put("time", "0");
                                    contentValues.put("json", new Gson().toJson(goodsInfo));
                                    int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=? and deptid=?",
                                            new String[]{goodsInfo.getFixedNumber(), departmentBeanList.get(departmentIndex).getDepartId()});
                                }
                            }
                            sqliteDatabase4.setTransactionSuccessful();
                            sqliteDatabase4.endTransaction();
                            changeView(state);
                        })
                        .setNegativeButton("取消", (dialogInterface, i1) -> {

                        }).create();
                alertDialog.show();
                break;
            case R.id.rlConfirmed:
                changeView(3);
                break;
            case R.id.llInventory:
                if (departmentIndex == 0) {
                    runOnUiThread(() -> getToast(context, "请先选择部门！"));
                    return;
                }
                if (!mInventoryStart) {
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                    builder1.setTitle("开始盘点")
                            .setMessage("确定要开始盘点吗")
                            .setNegativeButton("取消", (dialog, which) -> {
                                dialog.dismiss();

                            })
                            .setPositiveButton("确定", (dialogInterface, i) -> {
                                mInventoryStart = !mInventoryStart;
                                if (mInventoryStart) {
                                    tvWifi.setText("读取中");
                                    ivWifi.setImageResource(R.mipmap.red_wifi);
//                    Log.e(TAG, "onKeyDown: RfidGetPower===="+RfidGetPower() );
                                    ReadRFIDOne();
                                } else {
                                    tvWifi.setText("开始读取");
                                    ivWifi.setImageResource(R.mipmap.wifi);
                                    StopRFID();
                                }
                            })
                            .create()
                            .show();
                } else {
                    mInventoryStart = !mInventoryStart;
                    if (mInventoryStart) {
                        tvWifi.setText("读取中");
                        ivWifi.setImageResource(R.mipmap.red_wifi);
//                    Log.e(TAG, "onKeyDown: RfidGetPower===="+RfidGetPower() );
                        ReadRFIDOne();
                    } else {
                        tvWifi.setText("开始读取");
                        ivWifi.setImageResource(R.mipmap.wifi);
                        StopRFID();
                    }
                }
                break;
            case R.id.tvGoodNo:
                if (sortType != 1) {
                    tvGoodName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                    sortFlag = 0;
                }
                sortType = 1;
                changeImage();
                break;
            case R.id.tvGoodName:
                if (sortType != 2) {
                    tvGoodNo.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                    sortFlag = 0;
                }
                sortType = 2;
                /*if (sortFlag == 0) {
                    sortFlag = 1;
                } else {
                    if (sortFlag == 1) {
                        sortFlag = 2;
                    } else {
                        sortFlag = 1;
                    }
                }*/
                changeImage();
                break;
        }
    }

    private void changeImage() {
        Drawable drawable;
        if (sortFlag == 0) {
            sortFlag = 1;
            drawable = ContextCompat.getDrawable(this, R.drawable.up); // 替换为你的drawable资源
        } else {
            if (sortFlag == 1) {
                sortFlag = 2;
                drawable = ContextCompat.getDrawable(this, R.drawable.down); // 替换为你的drawable资源
//                tvGoodNo.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); // 设置drawableRight
            } else {
                sortFlag = 1;
                drawable = ContextCompat.getDrawable(this, R.drawable.up); // 替换为你的drawable资源
//                tvGoodNo.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); // 设置drawableRight
            }
        }
        if (sortType == 1) {
            tvGoodNo.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); // 设置drawableRight
        } else if (sortType == 2) {
            tvGoodName.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); // 设置drawableRight
        }
        changeView(state);
    }

    private void changeView(int status) {
//        runOnUiThread(() -> loadingDialog.show());
        state = status;
        tvUnpacked.setTextColor(ContextCompat.getColor(context, R.color.text333));
        tvDischarged.setTextColor(ContextCompat.getColor(context, R.color.text333));
        tvProfit.setTextColor(ContextCompat.getColor(context, R.color.text333));
        tvConfirmed.setTextColor(ContextCompat.getColor(context, R.color.text333));
        viewDischarged.setVisibility(View.GONE);
        viewUnpacked.setVisibility(View.GONE);
        viewProfit.setVisibility(View.GONE);
        viewConfirmed.setVisibility(View.GONE);
        tvOperation.setVisibility(View.GONE);

        tvGoodStatus.setVisibility(View.GONE);
        spinnerStatus.setVisibility(View.GONE);
        switch (status) {
            case 0://未盘
                tvUnpacked.setTextColor(ContextCompat.getColor(context, R.color.blue));
                viewUnpacked.setVisibility(View.VISIBLE);
                llNoProfit.setVisibility(View.VISIBLE);
                tvGoodStatus.setVisibility(View.VISIBLE);
                break;
            case 1://已盘
                tvDischarged.setTextColor(ContextCompat.getColor(context, R.color.blue));
                viewDischarged.setVisibility(View.VISIBLE);
                llNoProfit.setVisibility(View.VISIBLE);
                spinnerStatus.setVisibility(View.VISIBLE);
                break;
            case 2://盘盈
                tvProfit.setTextColor(ContextCompat.getColor(context, R.color.blue));
                viewProfit.setVisibility(View.VISIBLE);
                llNoProfit.setVisibility(View.GONE);
                tvGoodStatus.setVisibility(View.VISIBLE);
                break;
            case 3://待确认
                tvConfirmed.setTextColor(ContextCompat.getColor(context, R.color.blue));
                viewConfirmed.setVisibility(View.VISIBLE);
                llNoProfit.setVisibility(View.VISIBLE);
                tvOperation.setVisibility(View.VISIBLE);
                tvGoodStatus.setVisibility(View.VISIBLE);
                break;
        }
        sqliteDatabase4.beginTransaction();
        Cursor cursor;
        String orderBy = "";
        String sortF = "";
        if (sortFlag == 1) {
            sortF = "asc";
        } else {
            sortF = "desc";
        }
        switch (sortType) {
            case 1:
                orderBy = "number ";
                break;
            case 2:
                orderBy = "name ";
                break;
            default:
                orderBy = "time ";
                break;
        }
        orderBy = orderBy + sortF;
        switch (state) {
            case 0://未盘
            case 2://不存在当前数据的盘盈
                if (departmentIndex == 0) {
                    cursor = sqliteDatabase4.query("goods", null, "state=?",
                            new String[]{String.valueOf(status)},
                            null, null, orderBy);
                } else {
                    cursor = sqliteDatabase4.query("goods", null, "state=? and deptid=?",
                            new String[]{String.valueOf(status), departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, orderBy);
                }
                break;
            case 1://部门的盘存和盘盈
                if (departmentIndex == 0) {
                    cursor = sqliteDatabase4.query("goods", null, "state=? or state=?",
                            new String[]{"1", "3"},
                            null, null, orderBy);
                } else {
                    cursor = sqliteDatabase4.query("goods", null, "(state=? or state=?) and deptid=?",
                            new String[]{"1", "3", departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, orderBy);
                }
                break;
            case 3://待确认
                if (departmentIndex == 0) {
                    cursor = sqliteDatabase4.query("goods", null, "state=?",
                            new String[]{"4"},
                            null, null, orderBy);
                } else {
                    cursor = sqliteDatabase4.query("goods", null, "state=? and deptid=?",
                            new String[]{"4", departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, orderBy);
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + state);
        }

        list.clear();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
            GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
//            Log.e(TAG, "changeView: 获取的数据=========" + goodsInfo.toString());
            list.add(goodsInfo);
        }
        sqliteDatabase4.setTransactionSuccessful();
        sqliteDatabase4.endTransaction();
        switch (status) {
            case 0:
                tvUnpacked.setText("未盘（" + list.size() + "）");
                tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                break;
            case 1:
                tvDischarged.setText("已盘（" + list.size() + "）");
                tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                break;
            case 2:
                tvProfit.setText("盘盈（" + list.size() + "）");
                tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                tvConfirmed.setText("待确认（" + getStateSize(3) + "）");
                break;
            case 3:
                list.addAll(isConfirmList);
                tvConfirmed.setText("待确认（" + list.size() + "）");
                tvDischarged.setText("已盘（" + getStateSize(1) + "）");
                tvUnpacked.setText("未盘（" + getStateSize(0) + "）");
                tvProfit.setText("盘盈（" + getStateSize(2) + "）");
                break;
        }
        setAdapter();
//        loadingDialog.dismiss();
    }

    private int getStateSize(int state) {
        sqliteDatabase4.beginTransaction();
        Cursor cursor1;
        switch (state) {
            case 0:
            case 2:
                if (departmentIndex == 0) {
                    cursor1 = sqliteDatabase4.query("goods", null, "state=?",
                            new String[]{String.valueOf(state)},
                            null, null, null);
                } else {
                    cursor1 = sqliteDatabase4.query("goods", null, "state=? and deptid=?",
                            new String[]{String.valueOf(state), departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, null);
                }
                break;
            case 1:
                if (departmentIndex == 0) {
                    cursor1 = sqliteDatabase4.query("goods", null, "state=? or state=?",
                            new String[]{String.valueOf(state), "3"},
                            null, null, null);
                } else {
                    cursor1 = sqliteDatabase4.query("goods", null, "(state=? or state=?) and deptid=?",
                            new String[]{String.valueOf(state), "3", departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, null);
                }
                break;
            case 3:
                if (departmentIndex == 0) {
                    cursor1 = sqliteDatabase4.query("goods", null, "state=?",
                            new String[]{"4"},
                            null, null, null);
                } else {
                    cursor1 = sqliteDatabase4.query("goods", null, "state=? and deptid=?",
                            new String[]{"4", departmentBeanList.get(departmentIndex).getDepartId()},
                            null, null, null);
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + state);
        }
        int size = 0;
        while (cursor1.moveToNext()) {
            size++;
        }
        if (state == 3) {
            size = size + isConfirmList.size();
        }
        sqliteDatabase4.setTransactionSuccessful();
        sqliteDatabase4.endTransaction();
        return size;
    }

    //    初始化AUTOID UTouch(c)手持机
    public boolean InitRfid() {
//        Toast.makeText(context, R.string.init, Toast.LENGTH_SHORT).show();
        ///东集手持机
//        DisConnectRFID();
        try {
            UTouchUHF = UHFService.getInstance(this);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("初始化设备结果", "初始化设备");
//            Toast.makeText(context, R.string.Initialization_failure, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (UTouchUHF != null && UTouchUHF.open()) {
            init = true;
            byte[] embd = new byte[255];
            embd[0] = (byte) 2;
            embd[1] = (byte) 0;
            embd[2] = (byte) 12;
//            System.arraycopy(getHexByteArray(et_embeded_acpwd.getText().toString()), 0, embd, 3, 4);
            boolean IsSet = UTouchUHF.setParamBytes(UHFService.PARAMETER_TAG_EMBEDEDDATA, embd);
//            设置隐藏PC号
            boolean IsSetPC = UTouchUHF.setParameters(UHFService.PARAMETER_HIDE_PC, 1);
//            设置读取速度
            UTouchUHF.setParameters(UHFService.PARAMETER_INVENTORY_SPEED, 0);
            boolean IsSESSION = UTouchUHF.setParameters(UHFService.PARAMETER_INVENTORY_SESSION, 0);
            boolean IsProfile = UTouchUHF.setParameters(UHFService.PARAMETER_LINK_PROFILE, 1);
            Log.e("是否设置成功", "" + IsSESSION + ",隐藏PC" + IsSetPC + ",设置附加数据" + IsSet + ",灵敏度" + IsProfile);
            initKeyEventCallback();
//            UTouchUHF.registerReadTags(mIReadTagsListener);
//            int power = RfidGetPower();
//            spinner_setting.setSelection(power-1);
//            Toast.makeText(context, R.string.Initialization_successful, Toast.LENGTH_SHORT).show();
        } else {
            init = false;
//            Toast.makeText(context, R.string.Initialization_failure, Toast.LENGTH_SHORT).show();
        }
        return init;
    }

    // 设置AUTOID UTouch(c)手持机功率
    public void RfidSetPower(int Power) {
        ///东集手持机
        if (UTouchUHF != null) {
            boolean IsSet = false;
            // 设置功率
            IsSet = UTouchUHF.setPower(Power);
//            if(IsSet){
//                Toast.makeText(t, R.string.Success, Toast.LENGTH_SHORT).show();
//            }else{
//                Toast.makeText(context, R.string.Failure, Toast.LENGTH_SHORT).show();
//            }
            Log.e("设置功率:", "" + IsSet);
        }
    }

    // 查询AUTOID UTouch(c)手持机功率
    int Power = 0;

    public int RfidGetPower() {
        //、东集手持机
        if (UTouchUHF != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Power = UTouchUHF.getPower();
                    Log.e("模块功率:", "" + Power);
                }
            }).start();
            return Power;
        } else {
            return 0;
        }
    }

    // 销毁AUTOID UTouch(c)手持机模块
    public void DisConnectRFID() {
        ///东集手持机
        if (UTouchUHF != null) {// close uhf module
            mScanKeyService.unregisterCallback(mCallback);
            // 停止识别
            StopRFID();
            init = false;
            UTouchUHF.close();
//            UTouchUHF.unregisterReadTags(mIReadTagsListener);
            UTouchUHF = null;
        }
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        DisConnectRFID();
//    }

    //    开始单次读取
    public void ReadRFIDOne() {
        ///东集手持机
        if (UTouchUHF != null) {
            if (UTouchUHF.inventoryStart()) {
                Log.v("inventoryStart", "盘存开启成功");
                ThreadPoolManager.getInstance().executeTask(new Runnable() {
                    @Override
                    public void run() {
//                new Thread(() -> {
//                        mInventoryStart = true;
                        while (mInventoryStart) {
                            try {
                                Thread.sleep(100);
                                List<EPC> epcList = UTouchUHF.getTagIDs();
                                UTouchUHF.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST, 1);
                                if (epcList.size() > 0) {
                                    try {
                                        String TID = "";
                                        Log.v("EPC列表长度", "" + epcList.size() + "列表内容:" + epcList);
                                        for (int i = 0; i < epcList.size(); i++) {
                                            if (epcList.get(i).getId() != null && epcList.get(i).getId().length() > 4) {
                                                TID = epcList.get(i).getEmbeded();
                                                if (TID.contains("000000000000000000000000") || TID.isEmpty()) {
                                                    Log.e("TID不可用", "" + TID + "强度:" + epcList.get(i).rssi);
                                                } else {
                                                    String EPC = epcList.get(i).getId();
//                                                    ArrayList<String> ll = new ArrayList<>();
//                                                    switch (EPC) {
//                                                        case "E20000197310007624702C02":
//                                                            EPC = "AA2000000258";
//                                                            ll.add(EPC);
                                                    EPC = "AA2001061000098190000000";
//                                                            ll.add(EPC);
//                                                            break;
//                                                    }
                                                    EPC = EPC.toUpperCase();
                                                    Log.e(TAG, "run: EPC=======" + EPC);
                                                    if (epcStringList.indexOf(EPC) == -1) {
                                                        SoundTool.getInstance(InventoryActivity.this).playBeep(1);
                                                        epcStringList.add(EPC);
//                                                Log.e(TAG, "ReadRFIDOne: EPC=============" + EPC);

                                                        if (rbOnly.isChecked() && EPC.length() > 4 && !EPC.startsWith("AA4E")) {
                                                            continue;
                                                        }
                                                        if (rbNotOnly.isChecked() && EPC.length() > 4 && EPC.startsWith("AA4E")) {
                                                            continue;
                                                        }
//                                                        for (String epc : ll) {
                                                        queryInfo(EPC);
//                                                        }
                                                    }
//                                                setAdapter();
                                                }
                                            }
                                        }

                                    } catch (Exception e) {

                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
//                }).start();

                    }
                });
            } else {
                Log.v("inventoryStart", "盘存开启失败");
            }

        }
    }

    private void queryInfoByCode(String EPC) {
        SoundTool.getInstance(InventoryActivity.this).playBeep(1);
        Cursor cursor;
        cursor = sqliteDatabase4.query("goods", null, "number=?",
                new String[]{EPC},
                null, null, null);
//                                                List<GoodsInfo> ll = new ArrayList<>();
        GoodsInfo goodsInfo = null;
        while (cursor.moveToNext()) {
            @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
            goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
        }
//        Log.e(TAG, "queryInfo: goodsInfo == null" + (goodsInfo == null));
//        if(goodsInfo!=null) {
//            Log.e(TAG, "queryInfo: goodsInfo.getDeptid()" + goodsInfo.getDeptid());
//        }
        if (goodsInfo != null && !goodsInfo.getDeptid().isEmpty() && !goodsInfo.getStatus().equals("2") /*&&
                (goodsInfo.getStatus().equals("0")||goodsInfo.getStatus().equals("4"))*/) {
//            Log.e(TAG, "queryInfo: goodsInfo.getDeptid()======" + goodsInfo.getDeptid());
//            Log.e(TAG, "queryInfo: getDepartId()======" + departmentBeanList.get(departmentIndex).getDepartId());
//            Log.e(TAG, "queryInfo: =================================");
            //已盘
            if (goodsInfo.getDeptid().equals(departmentBeanList.get(departmentIndex).getDepartId())) {
                goodsInfo.setStatus("1");
                ContentValues contentValues = new ContentValues();
                contentValues.put("name", goodsInfo.getName());
                contentValues.put("number", goodsInfo.getCode());
                contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                contentValues.put("state", "1");
                contentValues.put("deptid", goodsInfo.getDeptid());
                contentValues.put("department", goodsInfo.getDepartment());
                contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                contentValues.put("time", System.currentTimeMillis());
                contentValues.put("json", new Gson().toJson(goodsInfo));
                int status = sqliteDatabase1.update("goods", contentValues, "number=?",
                        new String[]{EPC});
                Log.e(TAG, "ReadRFIDOne1: status=====" + status);
            } else {
                //存在条码的盘盈
                if (goodsInfo.getStatus().equals("0")) {
                    if (cbChange.isChecked()) {
                        goodsInfo.setStatus("3");
                        goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                        goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                    } else {
                        goodsInfo.setStatus("1");
                        goodsInfo.setDeptid(goodsInfo.getOldDeptid());
                        goodsInfo.setDepartment(goodsInfo.getOldDepartment());
                    }
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name", goodsInfo.getName());
                    contentValues.put("number", goodsInfo.getCode());
                    contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                    if (cbChange.isChecked()) {
                        contentValues.put("state", "3");
                        contentValues.put("deptid", goodsInfo.getDeptid());
                        contentValues.put("department", goodsInfo.getDepartment());
                    } else {
                        contentValues.put("state", "1");
                        contentValues.put("deptid", goodsInfo.getOldDeptid());
                        contentValues.put("department", goodsInfo.getOldDepartment());
                    }
                    contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                    contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                    contentValues.put("time", System.currentTimeMillis());
                    contentValues.put("json", new Gson().toJson(goodsInfo));
                    int status = sqliteDatabase1.update("goods", contentValues, "number=?",
                            new String[]{EPC});
                    Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                } else {
                    goodsInfo.setStatus("4");
                    isConfirmList.add(goodsInfo);
//                    goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
//                goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
//                    ContentValues contentValues = new ContentValues();
//                    contentValues.put("name", goodsInfo.getName());
//                    contentValues.put("number", goodsInfo.getCode());
//                    contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
//                    contentValues.put("state", "4");
//                    contentValues.put("deptid", goodsInfo.getDeptid());
//                    contentValues.put("department", goodsInfo.getDepartment());
//                    contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
//                    contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
//                    contentValues.put("json", new Gson().toJson(goodsInfo));
//                    int status = sqliteDatabase1.update("goods", contentValues, "number=?",
//                            new String[]{EPC});
//                    Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                }
            }
        } else {
            //
            if (goodsInfo == null) {
                goodsInfo = new GoodsInfo();
                goodsInfo.setCode(EPC);
                goodsInfo.setFixedNumber(EPC);
                goodsInfo.setStatus("2");
                goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                goodsInfo.setOldDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                goodsInfo.setOldDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                ContentValues values = new ContentValues();
                values.put("name", goodsInfo.getName());
                values.put("number", goodsInfo.getCode());
                values.put("fixedNumber", goodsInfo.getFixedNumber());
                values.put("state", "2");
                values.put("deptid", goodsInfo.getDeptid());
                values.put("department", goodsInfo.getDepartment());
                values.put("oldDeptid", goodsInfo.getOldDeptid());
                values.put("oldDepartment", goodsInfo.getOldDepartment());
                values.put("time", System.currentTimeMillis());
                values.put("json", new Gson().toJson(goodsInfo));
                long status1 = sqliteDatabase1.insert("goods", null, values);
            }
        }
        runOnUiThread(() -> changeView(state));
    }

    private void queryInfo(String EPC) {
        SoundTool.getInstance(InventoryActivity.this).playBeep(1);
        Cursor cursor;
        cursor = sqliteDatabase4.query("goods", null, "fixedNumber=?",
                new String[]{EPC},
                null, null, null);
//                                                List<GoodsInfo> ll = new ArrayList<>();
        GoodsInfo goodsInfo = null;
        while (cursor.moveToNext()) {
            @SuppressLint("Range") String json = cursor.getString(cursor.getColumnIndex("json"));
            goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
        }
        Log.e(TAG, "queryInfo: goodsInfo == ======" + goodsInfo);
//        if (goodsInfo != null) {
//            Log.e(TAG, "queryInfo: goodsInfo.getDeptid()" + goodsInfo.getDeptid());
//        }
        if (goodsInfo != null && !goodsInfo.getDeptid().isEmpty() && !goodsInfo.getStatus().equals("2")
            /*&& (goodsInfo.getStatus().equals("0")||goodsInfo.getStatus().equals("4"))*/) {
//            Log.e(TAG, "queryInfo: goodsInfo.getDeptid()======" + goodsInfo.getDeptid());
//            Log.e(TAG, "queryInfo: getDepartId()======" + departmentBeanList.get(departmentIndex).getDepartId());
//            Log.e(TAG, "queryInfo: =================================");
            if (goodsInfo.getDeptid().equals(departmentBeanList.get(departmentIndex).getDepartId())) {
                goodsInfo.setStatus("1");
                ContentValues contentValues = new ContentValues();
                contentValues.put("name", goodsInfo.getName());
                contentValues.put("number", goodsInfo.getCode());
                contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                contentValues.put("state", "1");
                contentValues.put("deptid", goodsInfo.getDeptid());
                contentValues.put("department", goodsInfo.getDepartment());
                contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                contentValues.put("time", System.currentTimeMillis());
                contentValues.put("json", new Gson().toJson(goodsInfo));
                int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                        new String[]{EPC});
                Log.e(TAG, "ReadRFIDOne1: status=====" + status);
            } else {
                if (goodsInfo.getStatus().equals("0")) {
                    if (cbChange.isChecked()) {
                        goodsInfo.setStatus("3");
                        goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                        goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                    } else {
                        goodsInfo.setStatus("1");
                        goodsInfo.setDeptid(goodsInfo.getOldDeptid());
                        goodsInfo.setDepartment(goodsInfo.getOldDepartment());
                    }
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name", goodsInfo.getName());
                    contentValues.put("number", goodsInfo.getCode());
                    contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
                    if (cbChange.isChecked()) {
                        contentValues.put("state", "3");
                        contentValues.put("deptid", goodsInfo.getDeptid());
                        contentValues.put("department", goodsInfo.getDepartment());
                    } else {
                        contentValues.put("state", "1");
                        contentValues.put("deptid", goodsInfo.getOldDeptid());
                        contentValues.put("department", goodsInfo.getOldDepartment());
                    }
                    contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
                    contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
                    contentValues.put("time", System.currentTimeMillis());
                    contentValues.put("json", new Gson().toJson(goodsInfo));
                    int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
                            new String[]{EPC});
                    Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                } else {
                    goodsInfo.setStatus("4");
                    isConfirmList.add(goodsInfo);
//                    goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
//                goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
//                    ContentValues contentValues = new ContentValues();
//                    contentValues.put("name", goodsInfo.getName());
//                    contentValues.put("number", goodsInfo.getCode());
//                    contentValues.put("fixedNumber", goodsInfo.getFixedNumber());
//                    contentValues.put("state", "4");
//                    contentValues.put("deptid", goodsInfo.getDeptid());
//                    contentValues.put("department", goodsInfo.getDepartment());
//                    contentValues.put("oldDeptid", goodsInfo.getOldDeptid());
//                    contentValues.put("oldDepartment", goodsInfo.getOldDepartment());
//                    contentValues.put("json", new Gson().toJson(goodsInfo));
//                    int status = sqliteDatabase1.update("goods", contentValues, "fixedNumber=?",
//                            new String[]{EPC});
//                    Log.e(TAG, "ReadRFIDOne2: status=====" + status);
                }
            }
        } else {
            if (goodsInfo == null && EPC.startsWith("AA")) {
                goodsInfo = new GoodsInfo();
                goodsInfo.setCode(EPC);
                goodsInfo.setFixedNumber(EPC);
                goodsInfo.setStatus("2");
                goodsInfo.setDeptid(departmentBeanList.get(departmentIndex).getDepartId());
                goodsInfo.setDepartment(departmentBeanList.get(departmentIndex).getDepartName());
                ContentValues values = new ContentValues();
                values.put("name", goodsInfo.getName());
                values.put("number", goodsInfo.getCode());
                values.put("fixedNumber", goodsInfo.getFixedNumber());
                values.put("state", "2");
                values.put("deptid", goodsInfo.getDeptid());
                values.put("department", goodsInfo.getDepartment());
                values.put("oldDeptid", goodsInfo.getOldDeptid());
                values.put("oldDepartment", goodsInfo.getOldDepartment());
                values.put("time", System.currentTimeMillis());
                values.put("json", new Gson().toJson(goodsInfo));
                long status1 = sqliteDatabase1.insert("goods", null, values);
            }
        }
        runOnUiThread(() -> changeView(state));
    }

    // 停止读取AUTOID UTouch(c)手持机
    public void StopRFID() {
        mInventoryStart = false;
        System.out.println("begin stop!!");
        ///东集手持机
        if (UTouchUHF.inventoryStop()) {
            System.out.println("end stop!!");
        } else {
            System.out.println("RfidInventoryStop faild.");
        }
    }

    public void initKeyEventCallback() {
        mScanKeyService = ScanKeyService.getInstance();
        mCallback = new IKeyEventCallback.Stub() {
            @Override
            public void onKeyDown(int i) throws RemoteException {
                Num++;
                if (i == 249 && scanner != null) {
                    scanner.startScan();
                }
                if (departmentIndex == 0) {
                    runOnUiThread(() -> getToast(context, "请先选择部门！"));
                    return;
                }
                Log.e(TAG, "onKeyDown: num==========" + Num);
                if (i == 250 && init) {
                    if (!mInventoryStart) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                                builder1.setTitle("开始盘点")
                                        .setMessage("确定要开始盘点吗")
                                        .setNegativeButton("取消", (dialog, which) -> {
                                            dialog.dismiss();

                                        })
                                        .setPositiveButton("确定", (dialogInterface, ss) -> {
                                            mInventoryStart = !mInventoryStart;
                                            if (mInventoryStart) {
                                                tvWifi.setText("读取中");
                                                ivWifi.setImageResource(R.mipmap.red_wifi);
//                    Log.e(TAG, "onKeyDown: RfidGetPower===="+RfidGetPower() );
                                                ReadRFIDOne();
                                            } else {
                                                tvWifi.setText("开始读取");
                                                ivWifi.setImageResource(R.mipmap.wifi);
                                                StopRFID();
                                            }
                                        })
                                        .create()
                                        .show();
                            }
                        });
                    } else {
                        mInventoryStart = !mInventoryStart;
                        if (mInventoryStart) {
                            tvWifi.setText("读取中");
                            ivWifi.setImageResource(R.mipmap.red_wifi);
//                    Log.e(TAG, "onKeyDown: RfidGetPower===="+RfidGetPower() );
                            ReadRFIDOne();
                        } else {
                            tvWifi.setText("开始读取");
                            ivWifi.setImageResource(R.mipmap.wifi);
                            StopRFID();
                        }
                    }
                }
            }

            @Override
            public void onKeyUp(int i) throws RemoteException {
                Num = 0;
//        Log.v("扫描摁键抬起", "" + i);
//        Log.v("抬起次数", "" + Num);
                if (i == 249 && scanner != null) {
                    scanner.stopScan();
                }
                if (i == 250 && init) {
//                    mInventoryStart = false;

                }
            }
        };
//            InitScanCallBack();
        Log.v("扫描器监听摁键对象", "" + mCallback);
        if (mScanKeyService != null) {
            mScanKeyService.registerCallback(mCallback, "249,250");
        }
        scanner = ScannerFactory.getScanner(this);
        scanner.open();
        scanner.setDecodeInfoCallBack(this);
    }

    @Override
    public void onDecodeComplete(DecodeInfo decodeInfo) {

        String EPC = decodeInfo.barcode;
        if (departmentIndex == 0) {
            runOnUiThread(() -> getToast(context, "请先选择部门！"));
            return;
        }
//        if (rbOnly.isChecked() && EPC.length() > 4 && !EPC.startsWith("AA4E")) {
//            return;
//        }
//        if (rbNotOnly.isChecked() && EPC.length() > 4 && EPC.startsWith("AA4E")) {
//            return;
//        }
        getToast(this, "读取成功！");
        switch (EPC) {
            case "E20000197310009412703D73":
                EPC = "AA2000000021000000000000";
                break;
        }
        queryInfoByCode(EPC);
    }

    @Override
    protected void onDestroy() {
        DisConnectRFID();
        super.onDestroy();
    }
}